package com.yiba.vpn.repository;

import com.yiba.vpn.domain.User;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;


/**
 * User类的CRUD操作
 * @author ScienJus
 * @date 2015/7/10.
 */
public interface UserRepository extends CrudRepository<User, Long> {

    public User findByUsername(String username);

    public User findByPlatformId(String platformId);

    public Long countByUuid(String uuid);

    public User findByAccount(String account);

    @Query(value="update t_user set push_token = ?2 where uuid = ?1 ",nativeQuery=true)
    @Modifying
    @Transactional
	public void updateByUuid(String uuid,String token);


    @Query(value="update t_user set push_token = ?2 where account = ?1 ",nativeQuery=true)
    @Modifying
    @Transactional
    public void updateByAccount(String account, String token);

    @Query(value="update t_user set country = ?2 where id = ?1 ",nativeQuery=true)
    @Modifying
    @Transactional
    public void updateCountryById(Long id, String country);

    @Query(value="SELECT t2.* FROM t_user t2 LEFT JOIN  t_service_expired t1 ON t1.account = t2.account WHERE t2.push_token IS NOT NULL AND t1.service_expired < NOW()",nativeQuery=true)
    List<User> queryTokenAndAccountFromExpired();
    
    @Query(value="SELECT t2.* FROM t_user t2 LEFT JOIN t_service_expired t1 ON t1.account = t2.account LEFT JOIN t_push t3 ON t3.account = t1.account WHERE t2.push_token IS NOT NULL AND t1.service_expired < NOW() and (t3.status = 0 or t3.status is null)",nativeQuery=true)
    List<User> queryTokenAndAccountByPushStatus();


    public User findByvpnId(String queryToken);

    @Query(value="update t_user set isactivity = 1 where account = ?1 and  isactivity =0",nativeQuery=true)
    @Modifying
    @Transactional
    Integer updateIsactivityByAccount(String account);

    @Query(value="update t_user set pwd = ?1 where account = ?2 and  pwd = ?3 ",nativeQuery=true)
    @Modifying
    @Transactional
    Integer updatePwdByAccountAndPwd(String newpwd ,String account ,String pwd);

    public User findByPlatformIdAndPwdAndIsactivity(String platformId,String pwd,Integer isactivity);

	public User findByVpnId(String vpnId);


    @Query(value="update t_user set wfee = wfee+?2 where account = ?1  and wfee <?3",nativeQuery=true)
    @Modifying
    @Transactional
    void updateWfeeByAccount(String invitationcode, int wfeenum, int maxwfeenum);
}
